package com.itrui.buyitbackend.controller;

import com.itrui.buyitbackend.common.Code;
import com.itrui.buyitbackend.common.Result;
import com.itrui.buyitbackend.pojo.MyCollection;
import com.itrui.buyitbackend.pojo.Product;
import com.itrui.buyitbackend.service.MyCollectionService;
import com.itrui.buyitbackend.util.SetProductPicHeader;
import com.sun.javafx.scene.control.ReadOnlyUnbackedObservableList;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/collection")
public class MyCollectionController {
    @Autowired
    private MyCollectionService myCollectionService;

    /**
     * 查找用户收藏
     * @param account
     * @return
     */
    @GetMapping("/{account}")
    public Result getAllCollection(HttpServletRequest request, @PathVariable Integer account){
        String url = request.getRequestURL().toString();
        List<MyCollection> allCollection = myCollectionService.getAllCollection(account);
        for (int i = 0; i < allCollection.size();i++){
            Product product = SetProductPicHeader.setOnlyProduct(allCollection.get(i).getCollectionPro(), url);
            allCollection.get(i).setCollectionPro(product);
            allCollection.get(i).setCollectionNum(myCollectionService.getCollectionNumInt(account));
        }

        return new Result(Code.GET_OK,allCollection,"查询成功");
    };

    /**
     * 删除用户收藏
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delCollection(@PathVariable Integer id){

        boolean flag = myCollectionService.delCollection(id);

        return new Result(flag?Code.DELETE_OK:Code.DELETE_ERR,flag?"删除成功":"删除失败");
    };



    /**
     * 添加收藏
     * @param myCollection
     * @return
     */
    @PostMapping
    public Result addCollection(@RequestBody MyCollection myCollection){
        myCollection.setCollectionCreatetime(new Date());
        boolean flag = myCollectionService.addCollection(myCollection);
        return new Result(flag?Code.SAVE_OK:Code.SAVE_ERR,flag?"添加成功":"添加失败");
    };

}
